﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Common;
using AIS.SDK.Handler;
using Common;
using Newtonsoft.Json.Linq;

namespace AISservice.Common
{
    public class SomeHandler
    {

        public static string GetToken(string username)
        {

            //return AISClientHandler.Instance.GetCurrentToken();
            string msg = (string )CacheUtil.Get(username);
            try
            {
                if (string.IsNullOrWhiteSpace(msg))
                    return "";    
                JObject obj = JObject.Parse(msg);

                return obj["data"]["token"].ToString();
            }
            catch (Exception x)
            {
                Log4Net.Error($"GetToken Expcetion:{x.Message}");
                return "";
            }


        }
        public static string GetToken(string username, string password)
        {
            Console.WriteLine($"{DateTime.Now.ToString()} Request  GetToken:{username} ");
            bool needValidate = true;
            string token = getfromCache(username);
            
            if (string.IsNullOrWhiteSpace(token))
            {
                //从文件取
                token = getfromFile($"{username}.cache");
                if (string.IsNullOrWhiteSpace(token))
                {
                    //文件也娶不到，就需要调用AIS获取了
                    token= AISClientHandler.Instance.Tokenrequest(username, password, "AISClient", "*ALL", GlobalVariables.GetAISenvironment()).JsonString;
                    CacheUtil.Set(username, token, 1800);
                    updateFile($"{username}.cache", token);
                    needValidate = false;
                }
            }
            JObject obj = JObject.Parse(token);
            if (needValidate)
            {
                bool response = AISClientHandler.Instance.ValidateToken(obj["data"]["token"].ToString());
                if (!response)//token 验证失败，则重新取一个
                {
                    token = AISClientHandler.Instance.Tokenrequest(username, password, "AISClient", "*ALL", GlobalVariables.GetAISenvironment()).JsonString;
                    obj=JObject.Parse(token);
                    CacheUtil.Set(username, token, 1800);
                    updateFile($"{username}.cache", token);
                }
            }
            Console.WriteLine($"{DateTime.Now.ToString()}  username:{username} Token:{token}");
            return obj["data"]["token"].ToString();

        }
        public static void LogToken(string s)
        {
            //if (DateTime.Now.Hour < 12)
            //    return;

            //if (s.Substring(s.Length-4).Contains(DateTime.Now.Second.ToString()))
            //    throw new global::Common.MQException("500", "Invalid Token: Please Request a New Token!");

            //if (s.Contains(DateTime.Now.Second.ToString()))
            //    throw new global::Common.MQException("500", "Non-Authoritative Information!");
             
            Log4Net.Debug($"Token:{s}");
            //
        }
        public static string GetDateFormat(string username,DateTime date)
        {
            string dateformat = "MM/dd/yyyy";
            dateformat=getfromFile($"{username}.cache");
            if (!string.IsNullOrWhiteSpace(dateformat))
            {
                JObject obj = JObject.Parse(dateformat);
                dateformat = obj["data"]["simpleDateFormat"].ToString();
            }

            dateformat = dateformat.Replace("yyyy",date.Year.ToString());
            dateformat = dateformat.Replace("yy", date.Year.ToString());
            dateformat = dateformat.Replace("MM", date.Month.ToString());
            dateformat = dateformat.Replace("dd", date.Day.ToString());
            return dateformat;
        }
        private static string getfromCache(string username)
        {
            string loginresponse = (string)CacheUtil.Get(username);
            if (!string.IsNullOrWhiteSpace(loginresponse))
            {
                updateFile($"{username}.cache",loginresponse);
                return loginresponse;
            }
            return null;

        }
        private static string getfromFile(string filepath)
        {
            if (!File.Exists(filepath))
            {
                return null;
            }
            Stream fs = File.Open(filepath, FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
            StreamReader streamReader = new StreamReader(fs);
            return streamReader.ReadToEnd();
        }
        private static void updateFile(string filepath, string content)
        {
            File.WriteAllText(filepath, content, System.Text.Encoding.UTF8);//将内容写进jon文件中
        }
        public static string Getenvironment(string username)
        {

            //return AISClientHandler.Instance.GetCurrentToken();
            string msg = (string)CacheUtil.Get(username);
            try
            {
                return GlobalVariables.GetAISenvironment();
                if (string.IsNullOrWhiteSpace(msg))
                    return "";
                JObject obj = JObject.Parse(msg);

                return obj["environment"].ToString();
            }
            catch (Exception x)
            {
                Log4Net.Error($"GetToken Expcetion:{x.Message}");
                return "";
            }


        }
        public static string translateMsg(string msg)
        {
            string rv = msg;
            if (msg.Contains(""))
                rv=" 认证失败，请检查用户名或密码";


            return rv;

        }
    }
}
